package org.yeasy.distributedsession.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.*;
import org.yeasy.distributedsession.interceptor.LoginInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * The type Session controller.
 *
 * @author yangyishe
 * @date 2023 -03-11 21:08
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private static final String JWT_KEY="yeasy";

    private static final String UID="uid";

    private static final String LOGIN_USER="login_user";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * Do test string.
     *
     * @return the string
     * @author yangyishe
     * @date 2023 -03-11 21:08
     */
    @GetMapping("test")
    public String doTest(){
        return "test";
    }

    /**
     * spring-session登录
     * Login string.
     *
     * @param username the username
     * @param password the password
     * @param session  the session
     * @return the string
     * @author yangyishe
     * @date 2023 -03-11 21:13
     */
    @GetMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session){
        session.setAttribute("login_user",username);
        return "login success";
    }

    /**
     * spring-session信息查询
     * Info string.
     *
     * @param session the session
     * @return the string
     * @author yangyishe
     * @date 2023 -03-11 21:13
     */
    @GetMapping("/info")
    public String info(HttpSession session){
        return "current user:"+session.getAttribute("login_user");
    }

    /**
     * Logout string.
     *
     * @param session the session
     * @return the string
     * @author yangyishe
     * @date 2023 -03-11 21:43
     */
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("login_user");
        return "logout success";
    }

    /**
     * 手动redis+token, 登录
     * Login with token string.
     *
     * @param username the username
     * @param password the password
     * @return the string
     * @author yangyishe
     * @date 2023 -03-11 21:37
     */
    @GetMapping("/loginWithToken")
    public String loginWithToken(@RequestParam String username,
                                 @RequestParam String password){

        String key="token_"+ UUID.randomUUID().toString();
        // timeout实现登录过一段时间后自动退出
        stringRedisTemplate.opsForValue().set(key,username,3600, TimeUnit.SECONDS);
        return key;
    }

    /**
     * 手动redis+token, 查看信息
     * Info with token string.
     *
     * @param token the token
     * @return the string
     * @author yangyishe
     * @date 2023 -03-11 21:37
     */
    @GetMapping("/infoWithToken")
    public String infoWithToken(@RequestHeader String token){

        return "当前登录的是:"+stringRedisTemplate.opsForValue().get(token);
    }

    /**
     * Logout with token string.
     *
     * @param token the token
     * @return the string
     * @author yangyishe
     * @date 2023 -03-11 21:47
     */
    @GetMapping("/logoutWithToken")
    public String logoutWithToken(@RequestHeader String token){
        Boolean isSuccess=stringRedisTemplate.delete(token);
        return "logout with token:"+isSuccess;
    }

    @GetMapping("/loginWithJwt")
    public String loginWithJwt(@RequestParam String username,
                               @RequestParam String password){
        Algorithm algorithm = Algorithm.HMAC256(JWT_KEY);
        String token = JWT.create()
                .withClaim("login_user", username)
                .withClaim(UID, 1)
                .withExpiresAt(new Date(System.currentTimeMillis() + 3600000))
                .sign(algorithm);
        return token;
    }

    @GetMapping("/infoWithJwt")
    public String infoWithJwt(HttpServletRequest request){
//        Algorithm algorithm = Algorithm.HMAC256(JWT_KEY);
//        JWTVerifier verifier = JWT.require(algorithm)
//                .build(); //Reusable verifier instance
//
//        try {
//            DecodedJWT jwt = verifier.verify(token);
//            request.setAttribute(UID, jwt.getClaim(UID).asInt());
//            request.setAttribute(LOGIN_USER, jwt.getClaim(LOGIN_USER).asString());
//            return jwt;
//        }catch (TokenExpiredException e) {
//            //token过期
//            throw new RuntimeException("token过期");
//        }catch (JWTDecodeException e) {
//            //解码失败，token错误
//            throw new RuntimeException("解码失败，token错误");
//        }

        return request.getAttribute(LoginInterceptor.LOGIN_USER).toString();
//        return j;
    }

    @GetMapping("/logoutWitJwt")
    public String logoutWithJwt(){
        // 无法主动登出
        return null;
    }

    @GetMapping("/addressWithJwt")
    public String address(HttpServletRequest request){
        return request.getAttribute(LoginInterceptor.UID).toString();
    }

}
